"""
条件变量用于线程之间的通信和同步，一个线程可以等待某个条件的满足，另一个线程可以在条件满足时通知等待的线程。

"""

import threading
import time

# 创建条件变量对象
condition = threading.Condition()
# 共享资源
ready = False


def consumer():
    global ready
    with condition:
        # 等待条件满足
        while not ready:
            print("Consumer is waiting...")
            condition.wait()
        print("Consumer is consuming...")


def producer():
    global ready
    time.sleep(2)  # 模拟生产过程
    with condition:
        ready = True
        # 通知等待的线程
        condition.notify()
        print("Producer has produced.")


# 创建消费者线程和生产者线程
consumer_thread = threading.Thread(target=consumer)
producer_thread = threading.Thread(target=producer)

consumer_thread.start()
producer_thread.start()

consumer_thread.join()
producer_thread.join()

print("All threads have finished.")
